import cPickle as Pickle
import os,subprocess
from location import Location
from share import Share

def load():
    locations = None
    if os.path.isfile("./locations.pkl"):
        locations = Pickle.load(open("locations.pkl", 'r'))
    if locations != None:
        return locations
    else:
        return {}

def save(locations):
    Pickle.dump(locations, open("locations.pkl", 'w'),True)

def get_net_ip():
            """Return net ip addr"""
            from urllib2 import urlopen
            try:
                ip =  urlopen("http://www.whatismyip.com/automation/n09230945.asp").read()
            except:    
                try:        
                    ip = urlopen("http://bandoine.hd.free.fr/what_is_my_ip.php").read()
                except:
                    return None  
            print ip
            return ip
        
def get_current_location(locations):
        ip = get_net_ip()
        for item in locations:
            if locations[item].domain == ip:
                return item,ip

def ping(host):
        cmd = "ping -c 1 " + host + " | grep time"
        ping = subprocess.Popen(cmd,0,"/bin/sh",None,subprocess.PIPE,subprocess.PIPE,None,False,True)
        (stdout,stderr) = ping.communicate()
        if ping.returncode == 0:
            splited_output = stdout.split('\n')[0].split(' ')
            for item in splited_output:
                if item.find('(') != -1:
                    ip = item.strip('():')
                elif item.find('time') != -1:
                    latency = item.split('=')[1]
                    return (ip,float(latency))
        else:
            pass
#            print stderr
            